/**
 * @author Jerome Monceaux
 * @version 1.0
 * 
 * A class to read analog data from IOIO board
 **/
package org.hh.common;

import ioio.lib.api.AnalogInput;
import ioio.lib.api.IOIO;
import ioio.lib.api.exception.ConnectionLostException;

public class AnalogReader extends HHObject {

	private IOIO fIoio = null;
	private AnalogInput fAnalogInput = null;
  float fVoltage = 0.f;
  private boolean fIsSimulation = false;
  private int fPin = 0;
	
	public AnalogReader(String fName, int pinNumber) {
		super(fName);
		fPin = pinNumber;
	}

	protected void finalize() throws Throwable
	{
		if( fAnalogInput != null)
			fAnalogInput.close();
	  super.finalize(); //not necessary if extending Object.
	} 
	

	public void initIOIO(boolean isSimulation, IOIO ioio) throws ConnectionLostException{
		fIsSimulation = isSimulation;

		if(fIsSimulation) return;
		
		fIoio = ioio;
		fAnalogInput = fIoio.openAnalogInput(fPin);
	}

  public void updateIOIO() throws InterruptedException, ConnectionLostException{
		if( fIsSimulation ) return;
		
		if( fIoio == null || 
				fAnalogInput == null
				) return;
		
		fVoltage = fAnalogInput.getVoltage();

		// Send the event to observers
		setChanged();
		notifyObservers(new Object[]{"onUpdatedValue", new Object[]{fVoltage}});
  }
}
